package cc.eddic.examinationsystem.dto;

import cc.eddic.examinationsystem.Role;
import cc.eddic.examinationsystem.domain.Student;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Getter
public class ThymeleafUserDetails implements UserDetails {

    public ThymeleafUserDetails(Student user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        if (null == authorities) {
            if (log.isInfoEnabled()) log.info("role of {} is {}", user.getName(), user.getRole());
            val authority = new SimpleGrantedAuthority(user.getRole().toString());

            authorities = new ArrayList<>();
            authorities.add(authority);
        }

        return authorities;
    }

    @Override
    public String getUsername() {
        return user.getEmployeeNo().toString();
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    private final Student user;

    private List<SimpleGrantedAuthority> authorities;

}
